var myID = 0;
var previewTimeout;

var table = $('<table>', { 'style': 'border:1px solid black; width: 90%; background:white' }).attr('align', 'center').append('<thead>');

function setUpButtons(){
	
	search();
	
	$('#controlArea').css({
		'margin-top': '115px',
		'height': $('#UserResultArea').height() 
	});
	
	
	$('#search_box').keyup(function(e) {
		if(e.keyCode == 13) {
			search();
		}
	});
	
	$('#PBCommunityLink').children('div').css({ 'background-color': '#b8b8b8', 'background-image': 'none' });
	
	// Link the create group button to the controller.
	$("#PBCreateGroup").bind('click', function(){
		getFragment("creategroup", function(data){
			// Display the form in facebox.
			jQuery.facebox(data);
			
			// Get the institutions the user is enrolled in & add to dropdown
			for(inst in PicBoard.institutions){ 
				// Populate the institution list
				if(PicBoard.institutions[inst]['instID'] != 1) $('#instOwnership').append( $("<option>", { value: PicBoard.institutions[inst]['instID'], text: PicBoard.institutions[inst]['name'] }) );
			}
			
			// Link the create button
			$("#PBButtonCheckCreateGroup").bind('click', function(){
				// Check with the remote server if the group already exists.
				
				var newGroup = {
					groupName: $('#groupName').val(),
					groupDescription: $('#groupDescription').val(),
					groupVisibility: $('input[type=radio][name=groupVisibility]:checked').val(),
					institution: $('#instOwnership').val()
				};
				
				// Has the user inputted all the data that is required?
				if(newGroup.groupName != "" && newGroup.groupVisibility != "" && newGroup.institution != ""){
					// Send the data off to the server.
					$.ajax({
						type: "POST",
						url: PicBoard.baseURL + "rsrc.php?req=createGroup",
						data: newGroup,
						dataType: 'json',
						success: function(data){
							if(data.statusCode == 200){
								window.location = "managegroup?id=" + data.groupID;
							}
						}
					});

				} else {
					// The user has not filled in all required fields.
					PicBoard.getTranslations(['lang_272_fillInFields'], function(data){
						alert(data.payload.lang_272_fillInFields);
					});
				}
				
			});
			
		});
		
	});
	
	$('#PBCreateInst').bind('click', function(){
		getFragment("createCommunity", function(data){
			jQuery.facebox(data);	
			
			$.each(PicBoard.managedGroups, function(i, v){
				// Already in a community?
				if(PicBoard.managedGroups[i][2] == 1){				
					$('#instOwnership').append(
						$("<option>", { text: PicBoard.managedGroups[i][1], value: parseInt(PicBoard.managedGroups[i][0]) })
					);
				}
			});			
			
			$('button#createInstitution').bind('click', function(){
				$.post(PicBoard.baseURL + "rsrc.php?req=addInstitution", $('form#createInstForm').serialize(), function(data){
					if(data.statusCode == 200){
						window.location = "home";
					} else {
						alert(data.message);
					}
				}, 'json');		
			});		
		});
	});	
	
}

function search(){
	$.ajax({
		url: PicBoard.baseURL + 'rsrc.php?req=searchCommunities',
		dataType:'json',
		data: $('form#searchForm').serialize(),
		success: function(data){
			if(data.statusCode == 200){
				myID = data.uID;
				//console.log(data.payload);
				$('#UserResultArea').html("");
				if(data.payload[0].length > 0) renderGroupList(data.payload[0]);
				if(data.payload.length > 1){
					if(data.payload[1].length > 0) renderCommunityList(data.payload[1]);
				}
			} else {
				alert(data.message);
			}
		},
		'type': 'post'
	});
	
}

function renderCommunityList(data){
	var thisTable = table.clone();
	$(thisTable).children('thead')
		.append($('<tr>').append(
				$('<th>', { text: 'Community' }),		
				$('<th>', { text: 'Description' }),
				$('<th>', { text: 'Admin' }),
				$('<th>', { text: 'Manage' })
			));
	$(thisTable).append('<tbody>');
	

	for(c in data){
		if(parseInt(data[c].userisAdmin) == 1){
			manageLink = $('<a>', { href: 'managecommunities?id=' + parseInt(data[c].instID) }).append($('<img>', { src: PicBoard.baseURL + 'images/gear.png', 'border': '0' }) );
		} else {
			manageLink = "";
		}
		
		$(thisTable).children('tbody').append($('<tr>').data('communityObject', {'identifier': parseInt(data[c].instID)  } ).append(
			$('<td>', { text: data[c].name }),
			$('<td>', { text: data[c].description }),			
			$('<td>', { text: data[c].adminName }),
			$('<td>', { html: manageLink })
			)
		);
	}

	$('#UserResultArea').append(thisTable);
	
	
}


function renderGroupList(data){
	var thisTable = table.clone();
	$(thisTable).children('thead')
		.append($('<tr>').append(
				$('<th>', { text: 'Group' }),
				$('<th>', { text: 'in Community' }),			
				$('<th>', { text: 'Description' }),
				$('<th>', { text: 'Admin' }),
				$('<th>', { text: 'Join' }),
				$('<th>', { text: 'Leave' }),
				$('<th>', { text: 'Manage' })
			));
	$(thisTable).append('<tbody>');
	
	for(c in data){
		if(parseInt(data[c].userisAdmin) == 1){
			manageLink = $('<a>', { href: 'managegroup?id=' + parseInt(data[c].gID) }).append($('<img>', { src: PicBoard.baseURL + 'images/gear.png', 'border': '0' }) );
		} else {
			manageLink = "";
		}
		
		if(parseInt(data[c].hasMembership) == 1){
			joinLink = "";
			leaveLink = $('<a>', { href: "#",
				click: function(){
					thisLink = this;
					sendData = {'action': 'leave', 'gID' : parseInt($(thisLink).data('groupObject').gID), 'l' : PicBoard.language};
					$.ajax({
						type: "POST",
						url: PicBoard.baseURL + "rsrc.php?req=groupAction",
						data: sendData,
						success: function(msg){
							jQuery.facebox(msg);
							
							// Bind the decline button to close the dialog box.
							$("#leave_group_decline").bind('click', function(){
								jQuery.facebox.close();
							});				
							
							// Bind the accept button to send off an AJAX request to confirm leaving the group.
							$("#leave_group_confirmation").bind('click', function(){
								urlParts = window.location.href.match(/=(\w)$/);
								toSend = {'action': 'confirmleave', 'gID' : parseInt($(thisLink).data('groupObject').gID), 'l' : PicBoard.language};
								jQuery.facebox.close()
								// Send the request
								$.ajax({
									type: "POST",
									url: PicBoard.baseURL + "rsrc.php?req=groupAction",
									data: toSend,
									success: function(msg){
										jQuery.facebox(msg.message);
									}
								});
							});
						}
					});
				
				}
			}).data('groupObject', data[c]).append($('<img>', { src: PicBoard.baseURL + 'images/chain--minus.png', 'border': '0' }) );
			
		} else {
			if(parseInt(data[c].invitationOnly) == 1){
				joinLink = "";
				leaveLink = "";			
			} else {
				joinLink = $('<a>', { href: "#",
					click: function(){

						sendData = {'action': 'join', 'gID' : parseInt($(this).data('groupObject').gID), 'l' : PicBoard.language};			
						thisLink = this;
						
						$.ajax({
							type: "POST",
							url: PicBoard.baseURL + "rsrc.php?req=groupAction",
							data: sendData,
							dataType: 'json',
							success: function(msg){
								//alert(msg);
								
								if(msg.statusCode == 200){
									// Success
									alert(msg.message);
									$(thisLink).remove();
								}
								
								if(msg.status == "failure"){
									alert(msg.message);
								}
								
							}
						}, 'json');

					}
				}).data('groupObject', data[c]).append($('<img>', { src: PicBoard.baseURL + 'images/chain--plus.png', 'border': '0' }) );
				
				leaveLink = "";
			}
		}
		
		$(thisTable).children('tbody').append($('<tr>').data('chartData', {'identifier': parseInt(data[c].gID)  } ).append(
			$('<td>', { text: data[c].name }),
			$('<td>', { text: data[c].instName }),			
			$('<td>', { text: data[c].description }),
			$('<td>', { text: data[c].adminName }),
			$('<td>', { html: joinLink }),
			$('<td>', { html: leaveLink }),
			$('<td>', { html: manageLink })
			)
		);
	}

	$('#UserResultArea').append(thisTable);
	
}


// Queue setUpButtons() to run when the document is ready.
PicBoard.addLoadEvent( "setUpButtons()" );